#!/usr/bin/env python3
"""
HEMC Validation CLI - Configuration Driven Approach
"""

import json  # noqa: I001
from pathlib import Path

import click
from pyauto.config.models import HEMCConfig
from pyauto.config.router import router
from pyauto.utils.tools import jsonprt
import pyauto.scripts  #  # noqa: F401

## Add src to path to allow imports
# sys.path.insert(0, str(Path(__file__).parent / "src"))
from pprint import pprint as pprt

_CWD = Path(__file__).parent
_LOGDIR = _CWD / 'logs'
## 创建日志目录
_LOGDIR.mkdir(parents=True, exist_ok=True)


##000000000000000000000000000000000000000 添加命令行选项
@click.command(help='HEMC post-processing toolkit.')
## option 是 命令行可选参数
@click.option(
    '-c',
    '--config',
    'json_config_path',
    type=click.Path(exists=False),  # 允许默认文件不存在
    default=Path.cwd() / 'config.json',
    show_default=True,
    help='JSON 配置文件路径',
)
def main(json_config_path):
    """JSON_CONFIG_PATH: path to the configuration file."""
    print(f'可用命令\n:{router.commands}')

    ## read from json config files
    json_p = Path(json_config_path).expanduser().resolve()
    json_in = json.loads(json_p.read_text())
    # click.echo(f'Config loaded: {json_in}')
    jsonprt('```[main]Config loaded:\n', json_in)

    config = HEMCConfig.model_validate(json_in)
    with open(_LOGDIR / 'config.log', encoding='utf8', mode='+wt') as logcfg:
        logcfg.write(config.model_dump_json(indent=2))

    ## 预先创建空目录
    config.project_paths.create_directories()

    try:
        ## 根据 json 中的配置，发送到不同的函数执行
        return router.dispatch_multi(config)
    except json.JSONDecodeError as e:
        print(f"Error parsing JSON: {e}")
        return
    except ValueError as e:
        print(f"Value error: {e}")
        return
    except Exception as e:
        print(f"Error executing command: {e}")
        import traceback

        traceback.print_exc()
        return


if __name__ == "__main__":
    main()
